import json
import logging

from django.http import JsonResponse
from django.shortcuts import render
from wxcloudrun.models import bind_user
from wxcloudrun.models import tmpobj

logger = logging.getLogger('log')

def clear():#删除原有的数据
    data = bind_user.objects.all()
    data.delete()

def savelog(str1):
    obj = tmpobj()
    obj.data = str(str1)
    obj.save()


def savedata(item):
    obj = bind_user()
    obj._id = item.get('_id')
    obj._openid = item.get('_openid')
    obj.gangwei = item.get('gangwei')
    obj.yingyeting = item.get('yingyeting')
    obj.name = item.get('name')
    obj.save()


def adddata(request, _):
    '''
    增加小区数据
    '''
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    print(body)
    rsp = JsonResponse({'code': 0, 'errorMsg': ''}, json_dumps_params={'ensure_ascii': False})
    if request.method == 'POST' or request.method == 'post':

        if (body['action'] == 'saveall'):
            clear() #删除原来的数据
            dataobj = body['data']
            for item in dataobj:
                savedata(item)
            body = {'code': 0, 'errorMsg': '用户信息更新完成'}

        rsp = JsonResponse(body, json_dumps_params={'ensure_ascii': False})
    else:
        rsp = JsonResponse({'code': -1, 'errorMsg': '请求方式错误'},
                           json_dumps_params={'ensure_ascii': False})
    logger.info('response result: {}'.format(rsp.content.decode('utf-8')))

    return rsp

